package org.example.rtc.config;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class MyWebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 当 WebSocket 连接建立时调用
        System.out.println("WebSocket connected: " + session.getId());
        session.sendMessage(new TextMessage("Welcome!"));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 当接收到客户端发送的消息时调用
        String payload = message.getPayload();
        System.out.println("Received message: " + payload);

        // 向客户端发送回复
        session.sendMessage(new TextMessage("Echo: " + payload));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 当 WebSocket 连接关闭时调用
        System.out.println("WebSocket closed: " + session.getId());
    }
}
